#!/bin/sh

# don't put anything before here or it will break debconf!

set -e	# exit on error
. /usr/share/debconf/confmodule # Source debconf library.

# just installed so library, so run ldconfig
ldconfig

if [ ! "$DEBIAN_FRONTEND" = "noninteractive" ] ; then

	# Fetching configuration from debconf
	db_get roboticscape/q_enable_dt
	ENABLE_DT=$RET
	db_get roboticscape/q_runonboot
	PROG=$RET

	# set something or nothing to run on boot. Default was 'none' which removes
	# any existing link. If 'existing' was selected then link is left alone
	echo "**********************************************"
	 # make sure /etc/roboticscape exists
	if [ ! -d "/etc/roboticscape" ]; then
		echo "making /etc/roboticscape"
		mkdir /etc/roboticscape
	fi
	if [ "$PROG" = "rc_blink" ]; then
		echo "setting rc_blink to run on boot"
		ln -s -f /usr/bin/rc_blink /etc/roboticscape/link_to_startup_program
	elif [ "$PROG" = "rc_balance" ]; then
		ln -s -f /usr/bin/rc_balance /etc/roboticscape/link_to_startup_program
		echo "setting rc_balance to run on boot"
	elif [ "$PROG" = "none" ]; then
		echo "setting nothing to run on boot"
		rm -f /etc/roboticscape/link_to_startup_program
	else
		echo "leaving current roboticscape startup program alone"
	fi

	# enable services
	echo "**********************************************"
	echo "systemctl daemon-reload"
	systemctl daemon-reload
	echo "Enabling roboticscape Service"
	systemctl enable roboticscape
	echo "Enabling rc_battery_monitor Service"
	systemctl enable rc_battery_monitor
	# try to start battery monitor, but ignore errors as this may not work
	echo "Starting rc_battery_monitor Service"
	set +e
	systemctl start rc_battery_monitor

	# leave error checking off when setting up device tree too
	if [ "$ENABLE_DT" = "true" ]; then
		echo "**********************************************"
		echo "Configuring Device Tree"
		configure_robotics_dt.sh
	fi

	echo "**********************************************"
	echo " "
	echo "Robotics Cape package installation complete."
	if [ "$ENABLE_DT" = "true" ]; then echo "Please reboot now." ; fi
	echo " "
	echo "**********************************************"

fi

exit 0
